import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Tag,Form, Modal, Input } from 'antd';
import request from '../../api/request';



function Index() {

    const [data,setData]=useState([])

    const [page,setPage]=useState(1)
    const [pageSize,setPageSize]=useState(10)
    const [count,setCount]=useState(0)

     const [isModalOpen, setIsModalOpen] = useState(false);

     const [title1,setTitle1]=useState('')

     const [form] = Form.useForm();
     const [editId,setEdidId]=useState('')
  

    const getData=()=>{
        request.get('/api/article/list',{
           params:{
             page,//页码
            pageSize,//每页显示条数
           }
        }).then((res)=>{
            // console.log(res.data);
            
            setData(res.data.rows)
            setCount(res.data.count)
        })
    }
    useEffect(()=>{
        getData()
    },[page,pageSize])


    // 点击新增按钮
    const add=()=>{
      setTitle1('新增')
      setIsModalOpen(true);
      form.resetFields()
    }

    // 点击编辑按钮
    const bj=(record)=>{
      setTitle1('编辑')
      setIsModalOpen(true);
      form.setFieldsValue(record)
      setEdidId(record.id)
    }
  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };


    const onFinish = (values) => {
      console.log('Success:', values);
      if(title1==='新增'){
          request.post('/api/article',{
          "title":values.title,//文章标题
          "content":values.content,//文章内容
          "tagList":["HTTP"],//标签  array[string]
          "categoryList":["HTTP"],//分类  array[string]
          "authorId":47529555//用户id 暂时写死47529555 登陆成功后返回的用
        }).then((res)=>{
          console.log(res);
          getData()
          setIsModalOpen(false);
          console.log('新增成功');
        })
      }else if(title1==='编辑'){
        request.put(`/api/article/${editId}`,{...values,id:editId}).then((res)=>{
          getData()
          setIsModalOpen(false);
          console.log('编辑成功');
        })
      }
    };

    const del=(record)=>{
      setData(data.filter((item)=>item.id!==record.id))
    }

const onFinishFailed= (errorInfo) => {
  console.log('Failed:', errorInfo);
};

// 搜索
const { Search } = Input; // 从Input对象中解构出Search组件
const onSearch = (value) => {
  request.get('/api/article/list',{
    params:{
      keyword:value,
    }
  }).then((res)=>{
      setData(res.data.rows)
  })
};

const search =(value)=>{
  request.get('/api/article/list',{
    params:{
      tag:value,
    }
  }).then((res)=>{
      setData(res.data.rows)
  })
}

// 重置
const [czs,setCzs]=useState('')
const [czss,setCzss]=useState('')
const cz=()=>{
  setCzs('')
  setCzss('')

  getData()

}




    const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    render: (text) => <a>{text}</a>,
  },
  {
    title: '用户名',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
  {
    title: '文章内容',
    dataIndex: 'content',
    key: 'content',
  },
  {
    title: '浏览量',
    dataIndex: 'viewCount',
    key: 'viewCount',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
  },
  {
    title: '标签',
    key: 'tags',
    dataIndex: 'tags',
    render: (_, { tags }) => (
      <>
        {tags.map((tag) => {
          return (
            <Tag key={tag.name}>
              {tag.name.toUpperCase()}
            </Tag>
          );
        })}
      </>
    ),
  },
  {
    title: '操作',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <Button onClick={()=>bj(record)}>编辑</Button>
        <Button onClick={()=>del(record)}>删除</Button>
      </Space>
    ),
  },
];

  return (
    <div>

       <Form
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"
  >
    <Button color='primary' variant='outlined' onClick={add}>新增</Button> 

    {/* <Search placeholder="input search text" onSearch={onSearch}  style={{ width: 200 }} enterButton /> */}
    <span>

      搜索标题、内容：
    <Search
      placeholder="input search text"
      allowClear
      enterButton="搜索"
      size="large"
      onSearch={onSearch}
      style={{ width: 200 }}
      value={czs}
      onChange={(e) => setCzs(e.target.value)}
    />
    </span>
      <span>
      搜索标签：<Search
      placeholder="input search text"
      allowClear
      enterButton="搜索"
      size="large"
      onSearch={search}
      style={{ width: 200 }}
      value={czss}
      onChange={(e) => setCzss(e.target.value)}
    />

    </span>
    

    <Button onClick={cz}>重置</Button>
  </Form>

  {/* 新增编辑弹框 */}
  <Modal
        title={title1}
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
        name="basic"
        form={form}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
              label="标题"
              name="title"
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="内容"
              name="content"
            >
              <Input />
            </Form.Item>

            <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>

      </Form>
            
       
      </Modal>

      <Table columns={columns} dataSource={data}
      pagination={
        {
            total:count,
            onChange:(page,pageSize)=>{
                setPage(page)
                setPageSize(pageSize)
            },
            showSizeChanger:true,
            showQuickJumper:true,
            showTotal:(total) => `Total ${total} items`
        }
      }
   
      />
    </div>
  )
}

export default Index
